﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyHocPhi.Model;
using QuanLyHocPhi.BLL;
using QuanLyHocPhi.GUI.DuLieu;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace QuanLyHocPhi.GUI.TacNghiep
{
    public partial class FormThongKeTheoNgay : FormBase
    {
        private DataTable tbb = null;
        private decimal tongTien = 0;
        private string fileName = "";
        int pgSize = 5;
        int currenPageIndex = 1;
        int toTalPage = 0;
        public FormThongKeTheoNgay()
        {
            InitializeComponent();
            fileName = string.Format("{0}\\TEMPLATES\\MauThongKeTheoNgay.xls",
                "D:\\");
           
            hienThiDanhDanhNguoiThu();
        }

        void hienThiDanhDanhNguoiThu()
        {
            var ds = BizNguoiSuDung.DanhSachNguoiThuTien();
            ds.Insert(0, new NguoiSuDung() { HoVaTen = "Tất cả", TenDangNhap = "-1" });
            cbNguoiThu.DataSource = ds;
            cbNguoiThu.ValueMember = "TenDangNhap";
            cbNguoiThu.DisplayMember = "HoVaTen";
        }

        private void bntIn_Click(object sender, EventArgs e)
        {
            DataTable tb = (DataTable)bdPhieuThu.DataSource;
            bool duLieuRong = tb.Rows.Count == 0 ? true : false;
            if (duLieuRong)
                MessageBox.Show("Hiện tại danh sách là rỗng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
            {
                #region Tiền xử lý
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("File mẫu MauThongKeTheoNgay.xls không tồn tại", "Lỗi");
                    return;
                }
                FileStream fs = null;
                try
                {
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                }
                catch (Exception)
                {
                    MessageBox.Show("File mẫu đang mở. Vui lòng đóng lại trước khi tiếp tục", "Lỗi");
                    return;
                }
                #endregion

                #region Lấy dữ liệu từ grid và form
                DataTable danhSach = (DataTable)bdPhieuThu.DataSource;
                #endregion

                #region Làm việc với file excel
                FormProgress frm = new FormProgress();
                frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
                {
                    HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
                    #region Khởi tạo
                    var sheet = templateWorkbook.GetSheet("sheet1");
                    var soLuongPhieuThu = danhSach.Rows.Count;
                    var row = sheet.GetRow(3);
                    var cell = row.GetCell(4);
                    cell.SetCellValue(string.Format("{0:dd/MM/yyyy}", dateFrom.Value.Date));
                    cell = row.GetCell(6);
                    cell.SetCellValue(string.Format("{0:dd/MM/yyyy}", dateTo.Value.Date));
                    cell = row.GetCell(10);
                    cell.SetCellValue(tongTien.ToString().FormatCurrency());
                    #endregion
                    #region Tạo các style cho phần hiển thị nội dung
                    var detailCellStyle = templateWorkbook.CreateCellStyle();
                    detailCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                    detailCellStyle.BorderBottom = CellBorderType.DASHED;
                    detailCellStyle.BorderLeft = CellBorderType.THIN;
                    detailCellStyle.BorderRight = CellBorderType.THIN;
                    var cellHoStyle = templateWorkbook.CreateCellStyle();
                    cellHoStyle.BorderBottom = CellBorderType.DASHED;
                    cellHoStyle.BorderLeft = CellBorderType.THIN;
                    var cellTenStyle = templateWorkbook.CreateCellStyle();
                    cellTenStyle.BorderBottom = CellBorderType.DASHED;
                    cellTenStyle.BorderRight = CellBorderType.THIN;

                    var detailCellStyleEnd = templateWorkbook.CreateCellStyle();
                    detailCellStyleEnd.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                    detailCellStyleEnd.BorderBottom = CellBorderType.THIN;
                    detailCellStyleEnd.BorderLeft = CellBorderType.THIN;
                    detailCellStyleEnd.BorderRight = CellBorderType.THIN;
                    var cellHoStyleEnd = templateWorkbook.CreateCellStyle();
                    cellHoStyleEnd.BorderBottom = CellBorderType.THIN;
                    cellHoStyleEnd.BorderLeft = CellBorderType.THIN;
                    var cellTenStyleEnd = templateWorkbook.CreateCellStyle();
                    cellTenStyleEnd.BorderBottom = CellBorderType.THIN;
                    cellTenStyleEnd.BorderRight = CellBorderType.THIN;

                    var cellTongSoStyle = templateWorkbook.CreateCellStyle();
                    var fontCellTongSo = templateWorkbook.CreateFont();
                    fontCellTongSo.IsItalic = true;
                    cellTongSoStyle.SetFont(fontCellTongSo);
                    var cellBottomStyle = templateWorkbook.CreateCellStyle();
                    cellBottomStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                    var fontCellBottomStyle = templateWorkbook.CreateFont();
                    fontCellBottomStyle.Boldweight = (short)FontBoldWeight.BOLD;
                    cellBottomStyle.SetFont(fontCellBottomStyle);
                    #endregion
                    #region Chèn nội dung danh sách phiếu thu
                    for (int j = 0; j < soLuongPhieuThu; j++)
                    {
                        DataRow dtRow = danhSach.Rows[j];
                        row = sheet.CreateRow(j + 6);
                        for (int k = 0; k <= 11; k++)
                        {
                            cell = row.CreateCell(k);
                            if (k == 9)
                            {
                                try
                                {
                                    cell.SetCellValue(dtRow[k] != null ? double.Parse(dtRow[k].ToString()) : 0);
                                }
                                catch
                                {
                                    
                                }
                            }
                            else
                                cell.SetCellValue(dtRow[k] != null ? dtRow[k].ToString() : "");
                            cell.CellStyle = (j == (soLuongPhieuThu - 1)) ? detailCellStyleEnd : detailCellStyle;
                        }
                    }
                    #endregion
                    #region Lưu ra file Excel mới
                    sheet.ForceFormulaRecalculation = true;
                    var tenfile = string.Format("{0}\\{1:ddMMyyyy}_{2:ddMMyyyy}.xls", Application.StartupPath, dateFrom.Value.Date, dateTo.Value.Date);
                    try
                    {
                        using (var fileData = new FileStream(tenfile, FileMode.Create))
                        {
                            templateWorkbook.Write(fileData);
                            fileData.Close();
                    #endregion
                            System.Diagnostics.Process.Start(tenfile);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Bạn đang mở file " + tenfile + ". Vui lòng đóng lại trước khi tiếp tục. " + ex.ToString());
                    }
                    fs.Close();
                #endregion
                };
                #region On complete
                frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
                {
                    if (oE.Error != null)
                    {
                        string msg = oE.Error.Message;
                        if (oE.Error.InnerException != null)
                            msg += oE.Error.InnerException.Message;
                        DialogUtils.ShowError(msg);
                    }

                };
                #endregion
                frm.StartWorking(this);
            }
        }

        private void bntThongKe_Click(object sender, EventArgs e)
        {
            currenPageIndex = 1;
            ThongKe();
        }

        private void ThongKe()
        {
            bool loiNgay = dateFrom.Value.Date > dateTo.Value.Date ? true : false;
            var nguoiThu = (NguoiSuDung)cbNguoiThu.SelectedItem;
            if (loiNgay)
            {
                MessageBox.Show("Thời gian nhập vào không hợp lệ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            pgSize = (int)numericUpDown1.Value;
            var dFrom = dateFrom.Value.Date;
            var tempDateFrom = dateTo.Value.Date;
            var dTo = new DateTime(tempDateFrom.Year, tempDateFrom.Month, tempDateFrom.Day, 23, 59, 59);
            int soBanGhi = 0;
            decimal getTongTien = 0;
            FormProgress frm = new FormProgress();
            frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
            {
                soBanGhi = nguoiThu.TenDangNhap == "-1" ? BizPhieuThu.GetSoBanGhi(dFrom, dTo) : BizPhieuThu.GetSoBanGhi(dFrom, dTo, nguoiThu);
                tinhTongTrang(soBanGhi);
                getTongTien = nguoiThu.TenDangNhap == "-1" ? BizPhieuThu.GetTongTienTheoThoiGian(dFrom, dTo) : BizPhieuThu.GetTongTienTheoThoiGian(dFrom, dTo, nguoiThu);
                var danhSachPhieuThu = nguoiThu.TenDangNhap == "-1" ? BizPhieuThu.GetDanhSachPhieuThuTheoThoiGian(dFrom, dTo, pgSize, currenPageIndex) : BizPhieuThu.GetDanhSachPhieuThuTheoThoiGian(dFrom, dTo, nguoiThu, pgSize, currenPageIndex);
                HienThi(danhSachPhieuThu);
            };
            frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
            {
                if (oE.Error != null)
                {
                    string msg = oE.Error.Message;
                    if (oE.Error.InnerException != null)
                        msg += oE.Error.InnerException.Message;
                    DialogUtils.ShowError(msg);
                }

            };
            frm.StartWorking(this);
            lbTongtien.Text = "Tổng tiền: " + getTongTien.ToString().FormatCurrency() + " đồng";
            lbSoPhieuThu.Text = "Số phiếu thu: " + soBanGhi.ToString().FormatCurrency();
            bdPhieuThu.DataSource = tbb;
            colSTT2.DataPropertyName = "STT";
            colMaSV.DataPropertyName = "MaSinhVien";
            colHHo.DataPropertyName = "Ho";
            colTen.DataPropertyName = "Ten";
            colLop.DataPropertyName = "LopGoc";
            colLopHocPhan.DataPropertyName = "LopHocPhan";
            colTruong.DataPropertyName = "Truong";
            //colMaPhieuThu.DataPropertyName = "MaPhieuThu";
            colQuyen.DataPropertyName = "Quyen";
            colSoPhieu.DataPropertyName = "SoPhieu";
            colSoTien.DataPropertyName = "SoTien";
            colNgayThu.DataPropertyName = "NgayThu";
            colNguoiThu.DataPropertyName = "NguoiThu";
            gridPhieuThu.AllowUserToAddRows = false;
            gridPhieuThu.AllowUserToDeleteRows = false;
            gridPhieuThu.AutoGenerateColumns = false;
            gridPhieuThu.ReadOnly = true;
            gridPhieuThu.DataSource = bdPhieuThu;
            button4.Text = "Trang cuối [" + toTalPage.ToString() + "]";
        }

        private void tinhTongTrang(int soBanGhi)
        {
            toTalPage = soBanGhi / pgSize;
            if (soBanGhi % pgSize != 0)
                toTalPage++;
        }

        void HienThi(List<PhieuThu> danhSachPhieuThu)
        {
            tbb = new DataTable();
            tongTien = 0;
            if (danhSachPhieuThu.Count > 0)
            {
                tbb.Columns.Add("STT", typeof(string));
                tbb.Columns.Add("MaSinhVien", typeof(string));
                //tbb.Columns.Add("MaPhieuThu", typeof(string));
                tbb.Columns.Add("Ho", typeof(string));
                tbb.Columns.Add("Ten", typeof(string));
                tbb.Columns.Add("LopGoc", typeof(string));
                tbb.Columns.Add("LopHocPhan", typeof(string));
                tbb.Columns.Add("Truong", typeof(string));
                tbb.Columns.Add("Quyen", typeof(string));
                tbb.Columns.Add("SoPhieu", typeof(string));
                tbb.Columns.Add("SoTien", typeof(string));
                tbb.Columns.Add("NgayThu", typeof(string));
                tbb.Columns.Add("NguoiThu", typeof(string));
                int stt = (currenPageIndex - 1) * pgSize;
                foreach (var pt in danhSachPhieuThu)
                {
                    if (pt.SinhVien == null)
                        pt.SinhVien = BizSinhVien.GetSinhVienByMaSinhVien(pt.MaSinhVien);
                    if (pt.SinhVien != null)
                    {
                        DataRow row = tbb.NewRow();
                        stt++;
                        row["STT"] = stt.ToString();
                        row["MaSinhVien"] = pt.MaSinhVien;
                        //row["MaPhieuThu"] = pt.MaPhieuThu;
                        row["Ho"] = pt.SinhVien.HoDem;
                        row["Ten"] = pt.SinhVien.Ten;
                        row["Quyen"] = pt.QuyenSo;
                        row["SoPhieu"] = pt.SoPhieuThu;
                        row["SoTien"] = pt.SoTien;// pt.SoTien.ToString().FormatCurrency();
                        tongTien += pt.SoTien;
                        row["Truong"] = pt.SinhVien.Lop.Truong.TenTruong;
                        row["NgayThu"] = string.Format("{0:dd/MM/yyyy}", pt.NgayThu);
                        row["NguoiThu"] = pt.NguoiSuDung.HoVaTen;
                        if (pt.SinhVien.MaLoai == (int)LoaiSinhVien.SinhVienKhongChuyen)
                        {
                            LopHocPhan lopHocPhan = BizLopHocPhan.GetLopHocPhanByMaLHP(pt.KC_MaLopHocPhan);
                            if (lopHocPhan != null)
                                row["LopHocPhan"] = lopHocPhan.TenLopHocPhan;
                            Lop lop = BizLopGoc.GetLopByMaLop(pt.SinhVien.KC_MaLop);
                            if (lop != null)
                                row["LopGoc"] = lop.TenLop;
                        }
                        tbb.Rows.Add(row);
                    }
                    else
                        MessageBox.Show("MSV: " + pt.MaSinhVien + ", MPT: " + pt.MaPhieuThu, "Lỗi");
                }

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (currenPageIndex != 1)
            {
                currenPageIndex = 1;
                ThongKe();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (currenPageIndex != toTalPage)
            {
                currenPageIndex = toTalPage;
                ThongKe();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (currenPageIndex < toTalPage)
            {
                currenPageIndex++;
                ThongKe();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (currenPageIndex > 1)
            {
                currenPageIndex--;
                ThongKe();
            }
        }

        private void bdPhieuThu_DataSourceChanged(object sender, EventArgs e)
        {
            DataTable tb = (DataTable)bdPhieuThu.DataSource;
            if (tb.Rows.Count == 0)
            {
                button1.Enabled = false;
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                button5.Enabled = false;
                bntIn.Enabled = false;
            }
            else
            {
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                bntIn.Enabled = true;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            var dFrom = dateFrom.Value.Date;
            var tempDateFrom = dateTo.Value.Date;
            var dTo = new DateTime(tempDateFrom.Year, tempDateFrom.Month, tempDateFrom.Day, 23, 59, 59);
            FormProgress frm = new FormProgress();
            frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
            {
                var danhSachPhieuThu = BizPhieuThu.GetDanhSachPhieuThuTheoThoiGian(dFrom, dTo);
                HienThi(danhSachPhieuThu);
            };
            frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
            {
                if (oE.Error != null)
                {
                    string msg = oE.Error.Message;
                    if (oE.Error.InnerException != null)
                        msg += oE.Error.InnerException.Message;
                    DialogUtils.ShowError(msg);
                }

            };
            frm.StartWorking(this);
            bdPhieuThu.DataSource = tbb;
            bntIn_Click(sender, e);
        }

        private void cbNguoiThu_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Không gì cả
        }

        private void dateFrom_ValueChanged(object sender, EventArgs e)
        {
            dateTo.Value = dateFrom.Value;
        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
